package com.ajx.ablibrary.net;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.logging.Logger;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class RetryIntercepter implements Interceptor {
    private static final String TAG = "RetryIntercepter";
    public int maxRetry;//最大重试次数
    private int retryNum = 0;//假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）

    public RetryIntercepter(int maxRetry) {
        this.maxRetry = maxRetry;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Log.e("retryNum=" , retryNum+"");
        Response response = chain.proceed(request);

        String content = response.body().string();
        String result = null;
        try {
            JSONObject jsonObject = new JSONObject(content);
            result = jsonObject.getString("result");
        } catch (JSONException e) {
            e.printStackTrace();
            throw new IOException("parase data error" + content);
        }

        okhttp3.MediaType mediaType = response.body().contentType();
        while (!response.isSuccessful() && retryNum < maxRetry) {
            retryNum++;
            Log.e("retryNum 2=" , retryNum+"");
            response = chain.proceed(request);
        }
        while(!("1".equals(result))&& retryNum < maxRetry){
            retryNum++;

            response = chain.proceed(request);

            ResponseBody responseBody = response.peekBody(1024 * 1024);
            Log.e("retryNum 1=" , retryNum+"，"+responseBody.string());
        }
        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, content))
                .build();
    }
}

